package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatClient extends Thread {
    private static int clientsNumber = 1234;

    public static synchronized int getClientsNumber() {
        return clientsNumber;
    }

    public void run() {
        clientsNumber++;
        try(final Socket socket = new Socket("localhost", 9999)) {

            new Thread() {
                private DataInputStream dis = new DataInputStream(socket.getInputStream());
                private String lastMessage;
                @Override public void run() {
                    while(true) {
                        try {
                            lastMessage = dis.readUTF();
                        } catch (IOException e) {break;}
                    }
                }
            }.start();

            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            dos.writeUTF("/reg " + clientsNumber + " " + clientsNumber);

            while(true) {
                dos.writeUTF("URGENT_MESSAGE");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
            }

        } catch (IOException e) {}
        clientsNumber--;
    }
}